import { Provide } from '@midwayjs/decorator';
import { Repository } from 'typeorm';
import { DBBase } from '../base/DBBase';
import { ErrCode } from '../common/ErrCode';
import { Tools } from '../common/Tools';
import { UserLoginDTO } from '../dto/user.dto';
import { UserEntity } from '../entity/user.entity';

@Provide()
export class UserService extends DBBase {
  public async registered(reginfo:UserLoginDTO):Promise<ErrCode>{
      let users:Repository<UserEntity> = await this.Repository({entities:UserEntity});
      let user:UserEntity = await users.findOne({select:['username'],where:{username:reginfo.username}});
      if(!user){
        let reg:UserEntity = new UserEntity();
        reg.regtime = Tools.timestamp;
        reg.lasttime = Tools.timestamp;
        reg.username = reginfo.username;
        reg.password =  Tools.md5(Tools.md5(reginfo.password));
        try{
          await users.insert(reg);
          return ErrCode.USER_REG_SUCCESS;
        }catch(e){
          //将错误 写入日志
          return ErrCode.USER_REG_FAIL;
        }
      }else{
        return ErrCode.USER_REG_EXIST;
      }
  }
  public async login(info:UserLoginDTO):Promise<ErrCode|UserEntity>{
      let users:Repository<UserEntity> = await this.Repository({entities:UserEntity});
      let user:UserEntity = await users.findOne({select:['id','username','password'],where:{username:info.username}});
      if(!user){
          return ErrCode.USER_NOT_FOUND;
      }else{
        let pwd = Tools.md5(Tools.md5(info.password));
        if(pwd == user.password){
          user.lasttime = Tools.timestamp;
          users.save(user);
          return user;
        }else{
          return ErrCode.USER_LGIN_FAIL_PWD;
        }
      }
  }
}
